package com.wlstock.funi.runnable;

import android.util.Log;

import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.dao.MyAccountStockDao;
import com.wlstock.funi.model.MyAccountStocks;
import com.wlstock.funi.utils.IOUtils;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.StockUtils;
import com.wlstock.funi.utils.StrUtils;
import com.wlstock.funi.utils.TimeUtils;
import com.wlstock.funi.utils.ToastUtils;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by admin on 16/6/18.
 */

public class SysHisTrade {

    public onResultListener listener = new onResultListener() {
        @Override
        public void onResult(RESULT_CODE code, ArrayList<MyAccountStocks> results) {
            switch (code){
                case RESULT_DATAS:
                    MyAccountStockDao.getInstance(FundApplication.getInstance()).upDateList(results);
                    ToastUtils.showMiddleMsg(FundApplication.getInstance(), "同步"+results.size()+"条持仓历史数据");
                    break;
                case RESULT_ERROR:
                    ToastUtils.showMiddleMsg(FundApplication.getInstance(), "同步失败");
                    break;
                case RESULT_EMPTY:
                    ToastUtils.showMiddleMsg(FundApplication.getInstance(), "无数据同步");
                    break;
                default:
                    break;
            }
        }
    };

    public static enum RESULT_CODE{
        RESULT_EMPTY,
        RESULT_ERROR ,
        RESULT_REDIRECT,
        RESULT_DATAS
    }

    /**
     * 同步2个时间段的交易,同时存放到本地
     * @param resultListener
     * @param startDate
     * @param endDate
     */
    private void request(final SysHisTrade.onResultListener resultListener,Date startDate, Date endDate){
        if (resultListener != null){
            listener = resultListener;
        }
        if (!FundApplication.isLogSuccess) {
            NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.ID_LOG_OUTDATE, "登陆失效，请重新登陆", "无法获取最新价格", R.drawable.ic_exception);
            ToastUtils.showMiddleMsg(FundApplication.getInstance(), "尚未登录，无法获取最新价格");
            return;
        }

        if (listener == null) {
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        StringBuffer sb = new StringBuffer();
        sb.append("https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=getHistoryDeal&strdate="+sdf.format(startDate)+"&enddate="+sdf.format(endDate));
        FundAsyTask<String, Void, ArrayList<MyAccountStocks>> task = new FundAsyTask<String, Void, ArrayList<MyAccountStocks>>();

        task.backListener = new FundAsyTask.TaskLitener<String, ArrayList<MyAccountStocks>>() {

            @Override
            public ArrayList<MyAccountStocks> doInBackground(String... params) {

                HttpClient client = new DefaultHttpClient();

                HttpGet hGet = new HttpGet(params[0]);
                hGet.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8*");
                hGet.addHeader("Accept-Encoding","gzip, deflate, sdch, br");
                hGet.addHeader("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6");
                hGet.addHeader("Cache-Control","max-age=0");
                hGet.addHeader("Content-Type","application/x-www-form-urlencoded");
                hGet.addHeader("Host","etrade.cs.ecitic.com");
                hGet.addHeader("Origin","https://etrade.cs.ecitic.com");
                hGet.addHeader("Cookie",FundApplication.cookie);
                hGet.addHeader("Upgrade-Insecure-Requests","1");
                hGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
                hGet.addHeader("X-Requested-With","XMLHttpRequest");

                try {
                    HttpResponse response = client.execute(hGet);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String result = IOUtils.is2Str(response.getEntity().getContent());
                        return parseHisDatas(result);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally{
                    client.getConnectionManager().shutdown();
                }
                return null;
            }
        };
        task.resultListener = new FundAsyTask.TaskResultListener<ArrayList<MyAccountStocks>>() {
            @Override
            public void onPostResult(ArrayList<MyAccountStocks> myAccountStockses) {
                if (myAccountStockses==null){
                    listener.onResult(RESULT_CODE.RESULT_ERROR,null);
                }else if (myAccountStockses.isEmpty()){
                    listener.onResult(RESULT_CODE.RESULT_EMPTY, null);
                }else {
                    listener.onResult(RESULT_CODE.RESULT_DATAS, myAccountStockses);
                }
            }
        };
        task.execute(sb.toString());



    }



    /**
     * 根据本地里面的历史记录进行同步,讲从本地的最后一个时间开始同步
     * @param listener
     */
    public void request(SysHisTrade.onResultListener listener){
        MyAccountStocks stock = MyAccountStockDao.getInstance(FundApplication.getInstance()).queryLastStockDay();
        if (stock!=null && stock.getServerTradeDate()!= null && !stock.getServerTradeDate().isEmpty()){
            try {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(stock.getServerTradeDate());
                request(listener, TimeUtils.getDateByDayOffset(startDate,-15), new Date());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {
            //同步endDate开始的2个月
            Date startDate = TimeUtils.getDateByMonthOffset(new Date(), -1);
            request(listener,startDate, new Date());
        }

    }

    public void request(){
        request(null);
    }

    /**
     *	同步历史数据
     * @param hisDatas
     */
    public ArrayList<MyAccountStocks> parseHisDatas(String hisDatas) {
        if (hisDatas == null){
            return null;
        }
        Pattern compile = Pattern.compile("记录个数：[0-9]*");
        Matcher matcher = compile.matcher(hisDatas);
        String totalCount = "";
        while(matcher.find()){
            totalCount = hisDatas.substring(matcher.start()+5, matcher.end());
        }
        if (!totalCount.isEmpty() && totalCount.equals("0")) {
            //判断是网络错误还是真的记录为0
            if (hisDatas.contains("网络错误")) {
                return null;
            }else if (hisDatas.contains("没有记录")) {
                return null;
            }
        }else if (!totalCount.isEmpty()){
            //总数量不为0
            Document doc = Jsoup.parse(hisDatas);
            Elements selItems = doc.select("[align=\"right\"]");
            //需要减去最后的一个
            Collections.reverse(selItems);
            if (selItems.size()-1 == Integer.valueOf(totalCount)) {
                ArrayList<MyAccountStocks> stocks = new ArrayList<>();
                ArrayList<String>  tmpStkCodes = new ArrayList<String>();
                for (Element oddRedItem : selItems) {
                    Elements childItems = oddRedItem.children();
                    //正确的item
                    if (childItems.size() == 14) {
                        String stkCode = StrUtils.trimString( ((TextNode)childItems.get(3).childNode(0)).text().toString());
                        String qty = StrUtils.trimString(((TextNode)childItems.get(7).childNode(0)).text().toString());
                        //过滤XX天报价等信息
                        if (StockUtils.isStkValid(stkCode)){
                            MyAccountStocks account = MyAccountStockDao.getInstance(FundApplication.getInstance()).queryMyAccountByCode(stkCode);
                            //保证前面的不会给后面历史的覆盖了
                            if (account != null &&!tmpStkCodes.contains(stkCode)&&"买入".equals(((TextNode)childItems.get(5).childNode(0)).text().toString().trim())) {
                                tmpStkCodes.add(stkCode);
                                account.setWithHisData(childItems);
                                stocks.add(account);
                            }
                        }

                    }
                    Log.i("TAG", "" + childItems.size());
                }
                return stocks;
            }
            else{
                //数量有误，仍然判定异常
                return null;
            }

        }
        return null;
    }


    public interface onResultListener{
        public void onResult(SysHisTrade.RESULT_CODE code, ArrayList<MyAccountStocks> results);
    }

}
